﻿Imports System.Activities
Imports System.Activities.Tracking
Imports System.Collections.Generic

Public Class VisualTrackingParticipant
    Inherits Tracking.TrackingParticipant

    Public Event TrackingRecordReceived As EventHandler(Of TrackingEventArgs)

    Public Property ActivityIdToWorkflowElementMap As Dictionary(Of String, activity)
    Public Property ActivityElementMap As Dictionary(Of Object, Debugger.SourceLocation)

    Protected Overrides Sub Track(ByVal record As System.Activities.Tracking.TrackingRecord, ByVal timeout As System.TimeSpan)
        OnTrackingRecordReceived(record, timeout)
    End Sub

    Protected Sub OnTrackingRecordReceived(ByVal record As TrackingRecord, ByVal timeout As TimeSpan)

        Dim resultArgs As New TrackingEventArgs With {.Record = record, .Timeout = timeout}
        Select Case True
            Case TypeOf record Is WorkflowInstanceRecord '100
            Case TypeOf record Is WorkflowInstanceUnhandledExceptionRecord '101
            Case TypeOf record Is WorkflowInstanceAbortedRecord '102

            Case TypeOf record Is ActivityStateRecord '103
                If ActivityIdToWorkflowElementMap IsNot Nothing Then
                    If ActivityIdToWorkflowElementMap.ContainsKey(DirectCast(record, ActivityStateRecord).Activity.Id) Then
                        resultArgs.Activity = ActivityIdToWorkflowElementMap.Item(DirectCast(record, ActivityStateRecord).Activity.Id)
                    End If
                End If
            Case TypeOf record Is ActivityScheduledRecord '104
                If ActivityIdToWorkflowElementMap IsNot Nothing Then
                    If ActivityIdToWorkflowElementMap.ContainsKey(DirectCast(record, ActivityScheduledRecord).Activity.Id) Then
                        resultArgs.Activity = ActivityIdToWorkflowElementMap.Item(DirectCast(record, ActivityScheduledRecord).Activity.Id)
                    End If
                End If
            Case TypeOf record Is FaultPropagationRecord '105
            Case TypeOf record Is CancelRequestedRecord '106
            Case TypeOf record Is BookmarkResumptionRecord '107
            Case TypeOf record Is CustomTrackingRecord '108,110,111

            Case TypeOf record Is WorkflowInstanceSuspendedRecord '112
            Case TypeOf record Is WorkflowInstanceTerminatedRecord '113

        End Select
        RaiseEvent TrackingRecordReceived(Me, resultArgs)

    End Sub
End Class
